package com.aptemo.webetek.server.handlers;

import java.util.List;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.commands.impl.AssignResultAction;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.shared.EventBean;
import com.aptemo.webetek.shared.TeamBean;
import com.aptemo.webetek.shared.UserBean;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;

public class AssignResultHandler
		extends ActionHandler<AssignResultAction, EventBean>
{

	public AssignResultHandler(DataStoreAPI service)
	{
		super(service);
	}

	public Class<? extends Action<?>> getActionType()
	{
		return AssignResultAction.class;
	}

	@Override
	public EventBean invoke(AssignResultAction action) throws BackendException, WebetekLoginException
	{
		utils.checkLogin();

		if (!utils.isTeamEditor(action.getTeamId()))
		{
			throw new BackendException(EErrorCodes.NOT_TEAM_EDITOR);
		}

		String pickkey = action.getPickKey();
		String comment = action.getDescription();

		if ((null == pickkey) || (pickkey.isEmpty()))
		{
			throw new BackendException(EErrorCodes.INVALID_ID, "PickId");
		}

		// assign pick
		EventBean event = dataService.assignResultPick(pickkey, comment);

		// complete stakes...
		List<UserBean> users = dataService.completeStakes(event.getKey());

		// notify users task...
		TeamBean team = dataService.getTeam(action.getTeamId());
		if (team.isNotifications())
		{
			for (UserBean user : users)
			{

				String content = "";
				content += "\r\n\r\nUser: " + user.getEmail() + " (" + team.getName() + ")";
				// TODO set content
				
				// task...
				//createEmailSenderTask("", user.getEmail(), "", "[Webetek] Bet completed...", content);
			}
		}

		return event;
	}

}
